<template>
  <div class="video-selector">
    <video
        ref="videoRef"
        :src="videoSrc"
        @timeupdate="updateProgress"
        @loadedmetadata="initDuration"
    ></video>

    <div class="timeline-container">
      <!-- 时间轴 -->
      <div
          class="timeline"
          @mousedown="handleTimelineClick"
      >
        <!-- 背景轨道 -->
        <div class="track-background"></div>

        <!-- 已选区 -->
        <div
            class="selection-range"
            :style="{
            left: fixedStartPercent + '%',
            width: (currentEndPercent - fixedStartPercent) + '%'
          }"
        ></div>

        <!-- 结束点拖动柄 -->
        <div
            class="end-handle"
            :style="{ left: currentEndPercent + '%' }"
            @mousedown="startDrag"
        ></div>

        <!-- 当前播放头 -->
        <div
            class="playhead"
            :style="{ left: playheadPercent + '%' }"
        ></div>
      </div>

      <!-- 时间显示 -->
      <div class="time-display">
        <span>当前: {{ formatTime(currentTime) }}</span>
        <span v-if="hasSelection">
          选区: {{ formatTime(fixedStartTime) }} - {{ formatTime(currentEndTime) }}
        </span>
        <span>总时长: {{ formatTime(duration) }}</span>
      </div>
    </div>

    <!-- 控制栏 -->
    <div class="controls">
      <button @click="togglePlay">
        {{ isPlaying ? '暂停' : '播放' }}
      </button>
      <button
          @click="playSelection"
          :disabled="!hasSelection"
      >
        播放选区
      </button>
      <button
          @click="clearSelection"
          :disabled="!hasSelection"
      >
        清除选区
      </button>
    </div>

    <!-- 新增评论功能区域 -->
    <div class="comment-section">
      <div class="comment-input">
        <input
            v-model="newComment"
            placeholder="输入评论..."
            @keyup.enter="addComment"
        >
        <button @click="addComment">添加评论</button>
      </div>

      <div class="comment-list">
        <div v-for="(comment, index) in comments" :key="index" class="comment-item">
          <div class="comment-time">
            {{ formatTime(comment.timestamp) }}
            <canvas class="comment-thumbnail" ref="thumbnailCanvases" />
          </div>
          <div class="comment-content">{{ comment.text }}</div>
        </div>
      </div>
    </div>

    <!-- 隐藏的截图Canvas -->
    <canvas ref="snapshotCanvas" style="display: none;"></canvas>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted, nextTick} from 'vue';

const props = defineProps({
  videoSrc: {
    type:String,
    default:'https://kujing-bos.bd.bcebos.com/dev/prepare/1912417862922702849/bea1d9ac4dc14fc9a066dad078a1ac3b.mp4'
  }
});

const videoRef = ref(null);
const duration = ref(0);
const currentTime = ref(0);
const isPlaying = ref(false);
const isDragging = ref(false);
const fixedStartPercent = ref(0);
const currentEndPercent = ref(0);

// 计算属性
const playheadPercent = computed(() => {
  return (currentTime.value / duration.value) * 100;
});

const hasSelection = computed(() => {
  return currentEndPercent.value > fixedStartPercent.value;
});

const fixedStartTime = computed(() => {
  return (fixedStartPercent.value / 100) * duration.value;
});

const currentEndTime = computed(() => {
  return (currentEndPercent.value / 100) * duration.value;
});

// 初始化视频时长
const initDuration = () => {
  duration.value = videoRef.value.duration;
};

// 更新播放进度
const updateProgress = () => {
  currentTime.value = videoRef.value.currentTime;

  // 自动暂停逻辑
  if (hasSelection.value && currentTime.value >= currentEndTime.value) {
    videoRef.value.pause();
    isPlaying.value = false;
  }
};

// 设置固定起始点
const setFixedStart = () => {
  if (isPlaying.value) return;

  fixedStartPercent.value = (currentTime.value / duration.value) * 100;
  currentEndPercent.value = fixedStartPercent.value + 1; // 初始设置1%宽度
};

// 处理时间轴点击
const handleTimelineClick = (e) => {
  if (!hasSelection.value) return;

  const rect = e.target.getBoundingClientRect();
  const clickPercent = ((e.clientX - rect.left) / rect.width) * 100;
  currentEndPercent.value = Math.max(fixedStartPercent.value, clickPercent);
};

// 开始拖动
const startDrag = (e) => {
  e.stopPropagation();
  isDragging.value = true;

  const moveHandler = (e) => {
    if (!isDragging.value) return;
    const rect = document.querySelector('.timeline').getBoundingClientRect();
    const percent = ((e.clientX - rect.left) / rect.width) * 100;
    currentEndPercent.value = Math.max(fixedStartPercent.value, Math.min(100, percent));
  };

  const upHandler = () => {
    isDragging.value = false;
    document.removeEventListener('mousemove', moveHandler);
    document.removeEventListener('mouseup', upHandler);
  };

  document.addEventListener('mousemove', moveHandler);
  document.addEventListener('mouseup', upHandler);
};

// 播放控制
const togglePlay = () => {
  if (videoRef.value.paused) {
    videoRef.value.play();
    isPlaying.value = true;
  } else {
    videoRef.value.pause();
    isPlaying.value = false;
    setFixedStart()
  }
};

// 播放选区
const playSelection = () => {
  if (!hasSelection.value) return;

  videoRef.value.currentTime = fixedStartTime.value;
  videoRef.value.play();
  isPlaying.value = true;
};

// 清除选区
const clearSelection = () => {
  fixedStartPercent.value = 0;
  currentEndPercent.value = 0;
};

// 时间格式化
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};


// 新增评论相关状态
const newComment = ref('');
const comments = ref([]);
const snapshotCanvas = ref(null);
const thumbnailCanvases = ref([]);

// 截图方法
const captureFrame = () => {
  const video = videoRef.value;
  const canvas = snapshotCanvas.value;

  if (!video || !canvas) return null;

  // 设置Canvas尺寸
  const width = 160;
  const height = 90;
  canvas.width = width;
  canvas.height = height;

  // 绘制视频帧
  const ctx = canvas.getContext('2d');
  ctx.drawImage(video, 0, 0, width, height);

  return canvas.toDataURL('image/jpeg', 0.8);
};

// 添加评论
const addComment = async () => {
  if (!newComment.value.trim()) return;

  // 捕获当前帧
  const screenshot = captureFrame();
  const timestamp = videoRef.value.currentTime;

  comments.value.push({
    text: newComment.value,
    timestamp,
    screenshot
  });

  // 更新缩略图显示
  await nextTick();
  updateThumbnails();

  newComment.value = '';
};

// 更新缩略图显示
const updateThumbnails = () => {
  thumbnailCanvases.value.forEach((canvas, index) => {
    if (!comments.value[index]) return;

    const img = new Image();
    img.src = comments.value[index].screenshot;
    img.onload = () => {
      const ctx = canvas.getContext('2d');
      canvas.width = 80;
      canvas.height = 45;
      ctx.drawImage(img, 0, 0, 80, 45);
    };
  });
};

</script>

<style scoped>
.video-selector {
  max-width: 800px;
  margin: 0 auto;
  background: #2d2d2d;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}

video {
  width: 100%;
  border-radius: 4px;
  margin-bottom: 15px;
}

.timeline-container {
  position: relative;
  padding: 10px 0;
}

.timeline {
  position: relative;
  height: 50px;
  cursor: pointer;
}

.track-background {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 4px;
  background: #404040;
  transform: translateY(-50%);
  border-radius: 2px;
}

.selection-range {
  position: absolute;
  top: 50%;
  height: 4px;
  background: rgba(33, 150, 243, 0.6);
  transform: translateY(-50%);
  border-radius: 2px;
  pointer-events: none;
}

.end-handle {
  position: absolute;
  top: 50%;
  width: 14px;
  height: 14px;
  background: #fff;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  cursor: ew-resize;
  box-shadow: 0 2px 6px rgba(0,0,0,0.3);
  transition: transform 0.2s;
}

.end-handle:hover {
  transform: translate(-50%, -50%) scale(1.2);
}

.playhead {
  position: absolute;
  top: 50%;
  width: 2px;
  height: 18px;
  background: #ff5252;
  transform: translate(-50%, -50%);
  z-index: 2;
}

.time-display {
  display: flex;
  justify-content: space-between;
  color: #fff;
  font-size: 13px;
  margin-top: 8px;
  padding: 0 5px;
}

.controls {
  display: flex;
  gap: 12px;
  margin-top: 15px;
  flex-wrap: wrap;
}

button {
  padding: 8px 16px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  flex: 1;
  min-width: 120px;
}

button:hover:not(:disabled) {
  background: #1976D2;
  transform: translateY(-1px);
}

button:disabled {
  background: #616161;
  cursor: not-allowed;
  opacity: 0.7;
}

.comment-section {
  margin-top: 20px;
  border-top: 1px solid #444;
  padding-top: 15px;
}

.comment-input {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.comment-input input {
  flex: 1;
  padding: 8px;
  border: 1px solid #444;
  border-radius: 4px;
  background: #333;
  color: #fff;
}
.comment-list {
  max-height: 300px;
  overflow-y: auto;
}

.comment-item {
  display: flex;
  gap: 15px;
  padding: 10px;
  background: #2d2d2d;
  border-radius: 4px;
  margin-bottom: 10px;
}

.comment-time {
  min-width: 120px;
  color: #888;
  font-size: 0.9em;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.comment-thumbnail {
  width: 80px;
  height: 45px;
  margin-top: 5px;
  border: 1px solid #444;
  border-radius: 2px;
}

.comment-content {
  flex: 1;
  padding: 5px;
  color: #fff;
}
</style>